package com.bawei.router.interceptor

import android.content.Context
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.bawei.base.RoutePath
import com.tencent.mmkv.MMKV

/**
 * Author: Jason Zhang
 * Date: 2024/12/14
 * Desc: 自定义路由拦截器
 */
@Interceptor(priority = 4, name = "路由Token拦截器")
class RouteTokenInterceptor: IInterceptor {

    private lateinit var mContext: Context

    //需要拦截Path路径
    private val needInterceptorPaths = arrayOf(RoutePath.PATH_MAIN_PAGE)

    /**
     * 初始化方法，只会执行一次
     */
    override fun init(context: Context?) {
        if (context != null) {
            mContext = context
        }
    }

    /**
     * 拦截操作
     */
    override fun process(postcard: Postcard, callback: InterceptorCallback) {
        if (needInterceptorPaths.contains(postcard.path)){
            var token = MMKV.defaultMMKV().decodeString("token", "")
            if (token.isNullOrEmpty()){
                //跳转到登录页面
                postcard.group = RoutePath.GROUP_LOGIN
                postcard.path = RoutePath.PATH_LOGIN_PAGE
                postcard.navigation()
            }
        }
        //继续执行跳转逻辑
        callback.onContinue(postcard)
    }


}